﻿'use strict';
/*
 常用的基础服务
*/
define(function(require , exports , module){
	angular.module("base" , ["ngRoute" , "App" , "dialogs"])
	.factory("tokenInterceptor" , function(){
		var tokenInterceptor = {
				request:function(config){
					if (!config.headers['Authorization']) {
						config.headers['Authorization'] = store.get("token");
					}
					return config;
				}
		};
		
		return tokenInterceptor;
	})
	.config(["$httpProvider" , function($httpProvider){
		$httpProvider.interceptors.push("tokenInterceptor");
	}])
	.factory("baseService" , function($rootScope , $dialogs , $location , $route ,  $http , $timeout , App){
		
		function BaseService() {

		};
		
		BaseService.prototype.request = function(url , method , param) {
			var $this = this;
			var params = param || {};
			return $http({
				method:method,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
				url:App.path + $this.transformUri(url),
				headers:{"Authorization":$this.getToken()},
				data: $.param(params)	
			})
			.then(function(res){
				return res.data;
			} , function(xhr){
				$this.checkError(xhr);
			});
		};

		BaseService.prototype.modify = function(url , method , param ,dialogHideFlag , callback) {
			var $this = this;
			var waitDlg = $dialogs.wait("请等待" , "数据处理中...");
			return $http({
				method:method,
				url:App.path + $this.transformUri(url),
                headers:{'Content-Type':'application/x-www-form-urlencoded',"Authorization":$this.getToken()},
                data: $.param(param)	
			})
			.then(function(res){
				waitDlg.close();
				if (res.data.status == App.statusCodes.ok || res.data.status == App.statusCodes.created) {
					  if(!dialogHideFlag){
						  $this.notify("提示信息" ,"操作成功");
					  }else{
	                      if (callback) {
	                    	  callback(res);
	                      }
	                      else {
	                    	  $this.notify("提示信息" ,"操作成功");
	                      }
					  }
                }
                else {
                	  if(!dialogHideFlag){
                		  $this.error("错误信息" , res.message);
                	  }else{
                		  console.log("错误信息");
                	  }
                      
                }
                return res.data;
			}  , function(xhr){
				waitDlg.close();
				$this.checkError(xhr);
				return xhr;
			});
		};


		BaseService.prototype.queryAll = function(domainName , params){
			var $this = this;
			var params = params || "";
			
			return $http({
				method:"GET",
				url: App.path + "/" + domainName + "/all?" + params,
				headers:{"Authorization":$this.getToken()}
			})
			.then(function(res){
				return res.data;
			} , function(xhr){
				$this.checkError(xhr);
			});
		};

		BaseService.prototype.get = function(domainName , id) {
			var $this = this;
			return $http({
				method:"GET",
				url:App.path + "/" + domainName + "/" + id,
				headers:{"Authorization":$this.getToken()}
			})
			.then(function(res){
                return res.data;
			} , function(){
				$this.error("错误信息" , "未知错误");
			});
		};

		BaseService.prototype.create = function(domainName , model) {
			var $this = this;
			var waitDlg = $dialogs.wait("请等待" , "数据处理中...");
			return $http({
				method:"POST",
				url:App.path + "/" + domainName,
                headers:{'Content-Type':'application/x-www-form-urlencoded',"Authorization":$this.getToken()},
                data: $.param(model)				
			})
			.then(function(res){
				waitDlg.close();
				
				if (res.data.status == App.statusCodes.created) {
                       $this.notify("提示信息" ,"成功");
                       $location.path("/" + domainName);
                }
                else {                	 
                      $this.error("错误信息" , res.message);
                }
                return res.data;
			} , function(e){
				waitDlg.close();
				if(e.data.message!=null){
					$this.error("错误信息" , e.data.message);
				}else{
					$this.error("错误信息" , "未知错误");
				}
			
			});
		};

		BaseService.prototype.update = function(domainName , id , model , callback) {
			var $this = this;
			var paramObj = angular.copy(model);
			delete paramObj.id;
			var waitDlg = $dialogs.wait("请等待" , "数据处理中...");
			return $http({
				method:"PUT",
				url:App.path + "/" + domainName + "/" + id,
                headers:{'Content-Type':'application/x-www-form-urlencoded',"Authorization":$this.getToken()},
                data: $.param(paramObj)	
			})
			.then(function(res){
				waitDlg.close();
				if (res.data.status == App.statusCodes.ok) {
                      if (callback) {
                    	  callback(res);
                      }
                      else {
                    	  $this.notify("提示信息" ,"操作成功");
                    	  $location.path("/" + domainName)
                      }
                }
                else {
                      $this.error("错误信息" , res.message);
                }
                return res.data;
			} , function(e){
				waitDlg.close();
				if(e.data.message!=null){
					$this.error("错误信息" , e.data.message);
				}else{
					$this.error("错误信息" , "未知错误");
				}
			});
		};

		BaseService.prototype.remove = function(domainName , id , callback , msg){
			var $this = this;
			var confirmMsg = msg?msg : "是否确认删除记录?";
			var dlg = $dialogs.confirm("删除确认" , confirmMsg);
				dlg.result.then(function(){
					var waitDlg = $dialogs.wait("请等待" , "数据处理中...");
					$http({
						method:"DELETE",
						url:App.path + "/" + domainName + "/" + id,
						headers:{"Authorization":store.get("token")},
					})
					.then(function(res){
						waitDlg.close();
		                if (res.data.status == App.statusCodes.ok) {
				              if (callback) {
				            	  callback(res);
				              }
				              else {
			                      $this.notify("提示信息" ,"操作成功");
			                      $route.reload();				            	  
				              }
		                }
		                else {
		                      $this.error("错误信息" , res.message);
		                }		                	
					} , function(xhr){
							waitDlg.close();
							$this.checkError(xhr);
					});			
			});

		};

		BaseService.prototype.checkError = function(xhr) {
			var $this = this;
			var status = xhr.status;
			var hasMessage = xhr.data && xhr.data.message;
			var message = xhr.data.message;
		
			switch(status) {
			case 500:
				$this.error("错误信息" , hasMessage?message:"未知错误");
				break;
			case 404:
				$this.error("错误信息" , hasMessage?message:"无法找到相关资源,请检查网络");
				break;
			case 403:
				$this.error("错误信息" , hasMessage?message:"您没有相关操作权限，请联系管理员");
				break;
			case 401:
				var dlg = $this.error("错误信息" , "请先登录系统(3秒后返回登录页)");
				$timeout(function(){
					window.location = "./login.html";
				},3000);
				break;
			case 400:
				$this.notify("提示信息", hasMessage?message:"错误的请求数据");
				break;
			default:
				$this.error("错误信息" , hasMessage?message:"未知错误...default");
				break;
			}				
		};

	    BaseService.prototype.error = function(title , content) {
	    	// 暂时用jquery方式判断是否已经打开了一个窗口
	    	if ($(".modal-dialog").size() == 0) {
	    		$dialogs.error(title , content);
	    	}
	    };

	    BaseService.prototype.notify = function(title , content) {
	    	//TODO 暂时用jquery方式判断是否已经打开了一个窗口
	    	if ($(".modal-dialog").size() == 0 ) {
	    		$dialogs.notify(title , content);
	    	}
	    };

	    BaseService.prototype.getToken = function() {
	    	//var token = store.get("token");
	    	return "";
	    };

	    BaseService.prototype.transformUri = function(uri){
	    	if (uri.substr(0 , 1) !== '/') {
	    		return '/' + uri;
	    	} 
	    	return uri;
	    };

		return new BaseService();
	});


});